import axios from 'axios'
import router from '@/router'
import { useUserStore } from '@/stores/index'

const baseURL = import.meta.env.DEV ? '/api' : 'http://localhost:8080'

// 白名单列表
const whiteList = ['/login']

const instance = axios.create({
  baseURL,
  timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const url = config.url || ''

    // 白名单直接放行
    if (whiteList.includes(url)) {
      return config
    }

    // 从 Pinia store 获取 token
    const userStore = useUserStore()
    const token = userStore.token // 直接获取 token
    console.log(token)

    if (token) {
      config.headers.authorization = token
    } else {
      // token 不存在且不在白名单中，跳转到登录页
      if (!whiteList.includes(url)) {
        router.push({
          path: '/login',
          query: { redirect: router.currentRoute.value.fullPath }
        })
      }
    }

    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.data.code === 1) {
      return response.data
    }
    return Promise.reject(new Error(response.data.msg || '操作失败'))
  },
  (error) => {
    if (error.response?.status === 401) {
      const userStore = useUserStore()

      // 清除 store 中的数据
      userStore.clearUser()

      // 跳转登录页
      router.push({
        path: '/login',
        query: {
          redirect: router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(error)
  }
)

export default instance
export { baseURL }
